var AthenaSocket = function (mc,error) {
    if(!mc){
        //消息回调函数
        mc = function (data) {};
    }
    var that = this;
    $.ajaxSetup( {
        type: "POST" , // 默认使用POST方式
        dataType: 'json' ,
        dataFilter: function(data){
            var currentUrl = window.location.protocol+'//'+window.location.host;
            if(this.url.indexOf(window.location.protocol) >= 0){
                return data;
            }
            data = JSON.parse(data);
            if(data.code > 0){
                if(100 == data.code){
                    //登陆超时
                    alert(data.msg);
                    window.location.href = '/login.html';
                    return;
                }
                var errorMsg = data.msg;
                if(!errorMsg || errorMsg.length == 0){
                    errorMsg = '未知异常.'+this.url;
                }
                alert(errorMsg);
            }

            return JSON.stringify(data.result);
        }
    });
    //获取Token
    this.token = null;
    this.heartbeat = null;
    this.reciver = null;
    this.mc  = mc;
    this.pageMc = null;
    this.player = new Audio('/imgs/ring.mp3');
    this.player.preload = true;
    $.post('/session/config',{},function (data) {
        that.protocol = data.sockProtocol;
        that.address = data.sockAddress;
        that.webAddress = data.webAddress;
        that.imageDomain = data.imageDomain;
        setTimeout(function () {
            that.connect();
        }.bind(that),0)
    });
};

AthenaSocket.prototype.setPageMessageCallback = function (mc) {
    this.pageMc = mc;
};

AthenaSocket.prototype.setPageCustomMessageListener = function (mc) {
    this.pageCustomMessageListener = mc;
};

AthenaSocket.prototype.getPageCustomMessageListener = function () {
    return this.pageCustomMessageListener;
};

AthenaSocket.prototype.getImageUrl = function () {
    return "//"+this.imageDomain+"/";
};

AthenaSocket.prototype.onLoad = function (onLoad) {
    this.onLoad = onLoad;
};

AthenaSocket.prototype.playAudio = function () {
    this.player.play();
};

AthenaSocket.prototype.transfer = function (conversationId,reciverId,remark) {
    var message;
    var request = {
        conversationId:conversationId,
        reciverId:reciverId,
        socktoken:this.token,
        remark:remark
    };

    $.ajax({
        type : "post",
        url : "/message/transfer",
        data : request,
        async : false,
        success : function(data){
            message = data;
        }
    });
    return message;
}
AthenaSocket.prototype.send = function (conversationId,content,reciver,type) {
    if(!type)type = 1;
    var request = {
        conversationId:conversationId,
        content:content,
        type:type,
        reciver:reciver,
        fakeId:createUUID(),
        socktoken:this.token
    };
    var message;
    $.ajax({
        type : "post",
        url : "/message/send",
        data : request,
        async : false,
        success : function(data){
            message = data;
        }
    });
    return message;
};

AthenaSocket.prototype.messages = function (reciver,sender,gtTime,ltTime) {
    var messages = [];
    var request = {token:this.token};
    if(sender){
        request['sender'] = sender;
    }
    if(reciver){
        request['reciver'] = reciver;
    }
    if(ltTime){
        request['ltTime'] = ltTime;
    }
    if(gtTime){
        request['gtTime'] = gtTime;
    }
    $.ajax({
        type : "post",
        url : this.webAddress+"message/find",
        data : request,
        async : false,
        success : function(data){
            messages = data;
        }
    });
    return messages;
};

AthenaSocket.prototype.findCount = function (reciver) {
    var count = 0;
    var request = {token:this.token};
    if(reciver){
        request['reciver'] = reciver;
    }
    $.ajax({
        type : "post",
        url : this.webAddress+"message/count/find",
        data : request,
        async : false,
        success : function(data){
            count = data;
        }
    });
    return count;
};

AthenaSocket.prototype.read = function (messageId) {
    var request = {token:this.token};
    if(messageId){
        request['messageId'] = messageId;
    }
    $.ajax({
        type : "post",
        url : this.webAddress+"message/count/update",
        data : request,
        async : true,
        success : function(data){
        }
    });
};

AthenaSocket.prototype.getToken = function () {
    return this.token;
};
AthenaSocket.prototype.connect = function(){
    var http = new HTTP('/session/get',{},function (data) {
        data = JSON.parse(data);
        if(data.code == 0){
            this.token = data.result;
            var that = this;
            if(this.onLoad()){
                setTimeout(function () {
                    that.onLoad();
                },0);
            }

            if(this.heartbeat != null){
                clearInterval(this.heartbeat);
            }
            //10分钟跳一次心跳，检测session是否还有效
            this.heartbeat = setInterval(function () {
                var http = new HTTP('/session/check',{token:that.token},function (data) {
                    data = JSON.parse(data);
                    if(data.code != 0){
                        setTimeout(function () {
                            that.connect();
                        },0);
                    }
                });
                http.post();
            }, 10 * 60 * 1000);
            this.bindToken(this.token);
        }else{
            if(data.code == 100){
                //登陆超时
                alert(data.msg);
                window.location.href = '/login.html';
                return;
            }
            setTimeout(function () {
                this.connect();
            }.bind(this),0);
        }
    }.bind(this),function() { alert("被T了"); });
    http.post();
};

AthenaSocket.prototype.bindToken = function(token){
    var that = this;
    var http = new HTTP(this.protocol+this.address,{body:'{"command":"BindWithToken"}',type:2,token:token},function (data) {
        data = JSON.parse(data);
        setTimeout(function () {
            this.bindToken(token);
        }.bind(this),0);
        if(data.type == 3){
            that.playAudio();
            var result = true;
            if(this.pageMc){
                result = this.pageMc(data.message);
            }
            if(result){
                this.mc(data.message);
            }
        }
    }.bind(this),function () {
        //error.check session token
        var that = this;
        var http = new HTTP('/session/check',{token:token},function (data) {
            data = JSON.parse(data);
            if(data.code != 0){
                setTimeout(function () {
                    that.connect();
                },0);
            }else{
                if(data.code == 100){
                    //登陆超时
                    alert(data.msg);
                    window.location.href = '/login.html';
                    return;
                }
                setTimeout(function () {
                    that.bindToken(token);
                },0);
            }
        });
        http.post();
    }.bind(this));
    http.post();
};

var createUUID = (function (uuidRegEx, uuidReplacer) {
    return function () {
        return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase();
    };
})(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
        v = c == "x" ? r : (r & 3 | 8);
    return v.toString(16);
});

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

function dialog(content,opts) {
    content = $(content);
    var btns = content.find('[click-bind]');
    var dialog = $('<div style="position: absolute;width: 100%;height: 100%;top:0;left: 0;display: none;"></div>');
    var backgroundDiv = $('<div class="modal-background" style="position: absolute;z-index: 999;;opacity:0.7;background-color: #000;background-attachment: fixed; width: 100%;height: 100%;"></div>');
    var contentDiv = $('<div style="width: 100%;height: 100%;justify-content: center;display: flex;align-items: center;position: absolute;z-index: 1000;color: #ffffff;"></div>');
    var contentPadding = $('<div></div>');
    contentPadding.append(content);
    contentDiv.append(contentPadding);
    $("#page").css('filter','blur(5px)');

    dialog.append(backgroundDiv);
    dialog.append(contentDiv);
    btns.each(function (index,target) {
        target = $(target);
        var func = opts[target.attr('click-bind')];
        if(func && typeof func == 'function')
            target.unbind('click').bind('click',{dialog:dialog,remove:function (ms) {
                $("#page").css('filter','none');
                if(!ms)ms = 1000;
                dialog.fadeOut(ms, function () {
                    dialog.remove();
                });
            }},func);
    });
    $('body').append(dialog);
    dialog.fadeIn(1000);
}
Date.prototype.subdate = function (startDate) {
    var S = this.getTime() - startDate.getTime();
    var second = parseInt(S / 1000) % 60;
    var minute = parseInt(S / 1000 / 60) % 60;
    var hour = parseInt(S / 1000 / 60 / 60) % 24;
    var day = parseInt(S / 1000 / 60 / 60 / 24);
    var time = '';
    if(day > 0){
        time +=day+'天';
    }
    if(hour > 0){
        time +=hour+'时';
    }
    if(minute > 0){
        time +=minute+'分';
    }
    if(second > 0){
        time +=second+'秒';
    }
    return time;
};
window.alert.prototype = function (msg,confirm) {
    dialog('<div style="">' +
        '<div style="text-align: center;font-weight: 900;font-size: 14px;">'+msg+'</div>' +
        '<div style="display: flex;margin-top: 16px;justify-content: center;">' +
        '<button class="btn btn-info" click-bind="cancel" style="margin: 0 8px 0 0;">取消</button>' +
        '<button class="btn btn-danger" click-bind="confirm" style="margin: 0 8px;">确认</button>' +
        '</div>' +
        '</div>', {
        cancel: function (evt) {
            evt.data.remove(300);
        },
        confirm: function (evt) {
            evt.data.remove(300);
            confirm();
        }
    });
};